<template>
	<div class="academic-achievement-overview">
		<div class="page-header">
			<h1 class="page-title">学术成果总览</h1>
		</div>

		<!-- 筛选条件 -->
		<el-card class="filter-card">
			<div class="filter-section">
				<el-row :gutter="20">
					<el-col :span="6">
						<el-form-item label="教师姓名">
							<el-input v-model="filters.teacherName" placeholder="输入教师姓名" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="论文类型">
							<el-select v-model="filters.type" placeholder="选择类型" clearable style="width: 100%;">
								<el-option label="全部类型" value="" />
								<el-option label="期刊论文" value="期刊论文" />
								<el-option label="会议论文" value="会议论文" />
								<el-option label="书评" value="书评" />
								<el-option label="报刊理论文章" value="报刊理论文章" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="期刊级别/分区">
							<el-select v-model="filters.journalLevel" placeholder="选择级别" clearable style="width: 100%;">
								<el-option label="全部级别" value="" />
								<el-option label="SCI一区" value="SCI一区" />
								<el-option label="SCI二区" value="SCI二区" />
								<el-option label="SCI三区" value="SCI三区" />
								<el-option label="SCI四区" value="SCI四区" />
								<el-option label="SSCI一区" value="SSCI一区" />
								<el-option label="SSCI二区" value="SSCI二区" />
								<el-option label="SSCI三区" value="SSCI三区" />
								<el-option label="SSCI四区" value="SSCI四区" />
								<el-option label="EI" value="EI" />
								<el-option label="CSSCI核心" value="CSSCI核心" />
								<el-option label="CSCD核心" value="CSCD核心" />
								<el-option label="北大核心" value="北大核心" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="发表年份">
							<el-date-picker v-model="filters.year" type="year" placeholder="选择年份" value-format="YYYY" style="width: 100%;" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="6">
						<el-form-item label="期刊/会议名称">
							<el-input v-model="filters.journalConference" placeholder="输入期刊或会议名称" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="作者类型">
							<el-select v-model="filters.authorType" placeholder="选择作者类型" clearable style="width: 100%;">
								<el-option label="全部作者" value="" />
								<el-option label="第一作者" value="第一作者" />
								<el-option label="通讯作者" value="通讯作者" />
								<el-option label="共同一作" value="共同一作" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="审核状态">
							<el-select v-model="filters.status" placeholder="选择状态" clearable style="width: 100%;">
								<el-option label="全部状态" value="" />
								<el-option label="待审核" value="PENDING" />
								<el-option label="已通过" value="APPROVED" />
								<el-option label="已驳回" value="REJECTED" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item>
							<el-button type="primary" @click="handleSearch">搜索</el-button>
							<el-button @click="resetFilters">重置</el-button>
							<el-button @click="debugData" type="info" size="small">调试数据</el-button>
						</el-form-item>
					</el-col>
				</el-row>
			</div>
		</el-card>

		<!-- 统计概览 -->
		<el-card class="stats-card">
			<div class="stats-section">
				<el-row :gutter="20">
					<el-col :span="6">
						<div class="stat-item">
							<div class="stat-number">{{ statistics.totalCount }}</div>
							<div class="stat-label">总成果数</div>
						</div>
					</el-col>
					<el-col :span="6">
						<div class="stat-item">
							<div class="stat-number">{{ statistics.journalCount }}</div>
							<div class="stat-label">期刊论文</div>
						</div>
					</el-col>
					<el-col :span="6">
						<div class="stat-item">
							<div class="stat-number">{{ statistics.conferenceCount }}</div>
							<div class="stat-label">会议论文</div>
						</div>
					</el-col>
					<el-col :span="6">
						<div class="stat-item">
							<div class="stat-number">{{ statistics.pendingCount }}</div>
							<div class="stat-label">待审核</div>
						</div>
					</el-col>
				</el-row>
				<el-row :gutter="20" style="margin-top: 20px;">
					<el-col :span="6">
						<div class="stat-item">
							<div class="stat-number">{{ statistics.sci1Count }}</div>
							<div class="stat-label">SCI一区</div>
						</div>
					</el-col>
					<el-col :span="6">
						<div class="stat-item">
							<div class="stat-number">{{ statistics.sci2Count }}</div>
							<div class="stat-label">SCI二区</div>
						</div>
					</el-col>
					<el-col :span="6">
						<div class="stat-item">
							<div class="stat-number">{{ statistics.ssci1Count }}</div>
							<div class="stat-label">SSCI一区</div>
						</div>
					</el-col>
					<el-col :span="6">
						<div class="stat-item">
							<div class="stat-number">{{ statistics.cssciCount }}</div>
							<div class="stat-label">CSSCI核心</div>
						</div>
					</el-col>
				</el-row>
			</div>
		</el-card>

		<!-- 成果列表 -->
		<el-card>
			<div class="table-header">
				<div class="table-title">学术成果列表</div>
				<div class="table-actions">
					<el-button type="primary" @click="exportData">导出数据</el-button>
				</div>
			</div>
			<el-table :data="filteredAchievements" stripe v-loading="loading" style="width: 100%">
				<el-table-column label="作者信息" width="200" show-overflow-tooltip>
					<template #default="{ row }">
						<div v-if="row.authors && row.authors.length > 0">
							<div v-for="author in row.authors.slice(0, 3)" :key="author.id" class="author-info">
								<span :class="{ 'first-author': author.authorOrder === '第一作者', 'corresponding-author': author.authorOrder === '通讯作者' }">
									{{ author.authorName }}
								</span>
								<span class="author-order">({{ author.authorOrder }})</span>
							</div>
							<div v-if="row.authors.length > 3" class="more-authors">
								+{{ row.authors.length - 3 }}位作者
							</div>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="title" label="论文标题" min-width="300" show-overflow-tooltip />
				<el-table-column prop="type" label="论文类型" width="120">
					<template #default="{ row }">
						<el-tag :type="getTypeTagType(row.type)" size="small">
							{{ row.type }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="journalConference" label="期刊/会议名称" min-width="200" show-overflow-tooltip />
				<el-table-column prop="journalLevel" label="期刊级别/分区" width="120" show-overflow-tooltip />
				<el-table-column prop="publicationYear" label="发表年份" width="100" />
				<el-table-column prop="status" label="审核状态" width="100">
					<template #default="{ row }">
						<el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="150" fixed="right">
					<template #default="{ row }">
						<el-button type="primary" size="small" @click="viewAchievement(row)">查看</el-button>
						<el-button v-if="row.status === 'PENDING'" type="warning" size="small" @click="reviewAchievement(row)">审核</el-button>
					</template>
				</el-table-column>
			</el-table>
			
			<!-- 分页 -->
			<div class="pagination-container">
				<el-pagination
					v-model:current-page="pagination.currentPage"
					v-model:page-size="pagination.pageSize"
					:page-sizes="[10, 20, 50, 100]"
					:total="pagination.total"
					layout="total, sizes, prev, pager, next, jumper"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</div>
		</el-card>

		<!-- 查看详情对话框 -->
		<el-dialog v-model="showViewDialog" title="学术成果详情" width="800px">
			<el-descriptions :column="2" border>
				<el-descriptions-item label="论文标题">{{ viewData.title }}</el-descriptions-item>
				<el-descriptions-item label="论文类型">{{ viewData.type }}</el-descriptions-item>
				<el-descriptions-item label="发表语言">{{ viewData.language }}</el-descriptions-item>
				<el-descriptions-item label="发表年份">{{ viewData.publicationYear }}</el-descriptions-item>
				<el-descriptions-item label="发表月份">{{ viewData.publicationMonth }}</el-descriptions-item>
				<el-descriptions-item label="DOI号">{{ viewData.doi }}</el-descriptions-item>
				<el-descriptions-item label="期刊级别">{{ viewData.journalLevel }}</el-descriptions-item>
				<el-descriptions-item label="会议级别">{{ viewData.conferenceLevel }}</el-descriptions-item>
				<el-descriptions-item label="关键词" :span="2">{{ viewData.keywords }}</el-descriptions-item>
				<el-descriptions-item label="期刊/会议名称" :span="2">{{ viewData.journalConference }}</el-descriptions-item>
			</el-descriptions>
			
			<!-- 作者信息 -->
			<div class="authors-section" style="margin-top: 20px;">
				<h4>作者信息</h4>
				<el-table :data="viewData.authors || []" border>
					<el-table-column prop="authorName" label="姓名" width="120" />
					<el-table-column prop="authorUnit" label="单位" min-width="200" />
					<el-table-column prop="authorOrder" label="署名顺序" width="100" />
					<el-table-column prop="staffNo" label="工号" width="100" />
					<el-table-column label="是否本单位" width="100">
						<template #default="{ row }">
							<el-tag :type="row.isCurrentUnit ? 'success' : 'info'">
								{{ row.isCurrentUnit ? '是' : '否' }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="是否本系" width="100">
						<template #default="{ row }">
							<el-tag :type="row.isCurrentDepartment ? 'success' : 'info'">
								{{ row.isCurrentDepartment ? '是' : '否' }}
							</el-tag>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</el-dialog>

		<!-- 审核对话框 -->
		<el-dialog v-model="showReviewDialog" title="审核学术成果" width="500px">
			<el-form :model="reviewForm" label-width="100px">
				<el-form-item label="审核结果">
					<el-radio-group v-model="reviewForm.status">
						<el-radio value="APPROVED">通过</el-radio>
						<el-radio value="REJECTED">驳回</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="审核意见">
					<el-input v-model="reviewForm.opinion" type="textarea" :rows="4" placeholder="请输入审核意见" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="showReviewDialog = false">取消</el-button>
				<el-button type="primary" @click="submitReview" :loading="reviewing">提交审核</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import {
	getAllAcademicAchievements,
	getAcademicAchievement,
	reviewAcademicAchievement,
	getTeachersList,
	searchByAuthorName
} from '@/api/academicAchievement'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const reviewing = ref(false)
const showViewDialog = ref(false)
const showReviewDialog = ref(false)
const achievements = ref([])
const viewData = ref({})
const currentReviewAchievement = ref(null)

// 筛选条件
const filters = reactive({
	teacherName: '',
	type: '',
	journalLevel: '',
	year: '',
	journalConference: '',
	authorType: '',
	status: ''
})

// 教师列表
const teacherList = ref([])

// 统计信息
const statistics = reactive({
	totalCount: 0,
	journalCount: 0,
	conferenceCount: 0,
	pendingCount: 0,
	sci1Count: 0,
	sci2Count: 0,
	ssci1Count: 0,
	cssciCount: 0
})

// 分页
const pagination = reactive({
	currentPage: 1,
	pageSize: 20,
	total: 0
})

// 审核表单
const reviewForm = reactive({
	status: 'APPROVED',
	opinion: ''
})

// 计算属性
const filteredAchievements = computed(() => {
	let result = achievements.value

	if (filters.teacherName) {
		// 如果搜索作者姓名，使用专门的搜索逻辑
		// 这里我们暂时保持原有的逻辑，但后续会改进
		result = result.filter(item => {
			// 根据创建者ID查找对应的教师姓名
			const teacher = teacherList.value.find(t => String(t.id) === String(item.createdBy))
			if (teacher) {
				return teacher.name.includes(filters.teacherName)
			}
			return false
		})
	}

	if (filters.type) {
		result = result.filter(item => item.type === filters.type)
	}

	if (filters.journalLevel) {
		result = result.filter(item => item.journalLevel === filters.journalLevel)
	}

	if (filters.year) {
		result = result.filter(item => item.publicationYear === parseInt(filters.year))
	}

	if (filters.journalConference) {
		result = result.filter(item => 
			item.journalConference && item.journalConference.includes(filters.journalConference)
		)
	}

	if (filters.authorType) {
		result = result.filter(item => 
			item.authors && item.authors.some(author => author.authorOrder === filters.authorType)
		)
	}

	if (filters.status) {
		result = result.filter(item => item.status === filters.status)
	}

	return result
})

// 方法
const fetchAchievements = async () => {
	try {
		loading.value = true
		const response = await getAllAcademicAchievements()
		achievements.value = Array.isArray(response) ? response : (response?.data || [])
		pagination.total = achievements.value.length
		calculateStatistics()
	} catch (error) {
		console.error('获取学术成果列表失败:', error)
		ElMessage.error('获取学术成果列表失败')
	} finally {
		loading.value = false
	}
}

// 根据作者姓名搜索成果
const searchByAuthorNameHandler = async (authorName) => {
	if (!authorName || authorName.trim() === '') {
		// 如果搜索词为空，显示所有成果
		await fetchAchievements()
		return
	}
	
	try {
		loading.value = true
		// 调用后端API搜索作者姓名
		const response = await searchByAuthorName(authorName.trim())
		const achievementIds = Array.isArray(response) ? response : (response?.data || [])
		
		if (achievementIds.length === 0) {
			// 如果没有找到结果，清空列表
			achievements.value = []
			pagination.total = 0
			ElMessage.info(`未找到作者"${authorName}"的学术成果`)
		} else {
			// 根据找到的成果ID筛选成果列表
			const allAchievements = await getAllAcademicAchievements()
			const allAchievementsList = Array.isArray(allAchievements) ? allAchievements : (allAchievements?.data || [])
			
			achievements.value = allAchievementsList.filter(item => 
				achievementIds.includes(item.id)
			)
			pagination.total = achievements.value.length
			ElMessage.success(`找到${achievements.value.length}个学术成果`)
		}
		
		calculateStatistics()
	} catch (error) {
		console.error('搜索作者姓名失败:', error)
		ElMessage.error('搜索失败')
	} finally {
		loading.value = false
	}
}

const fetchTeachers = async () => {
	try {
		const response = await getTeachersList()
		teacherList.value = Array.isArray(response) ? response : (response?.data || [])
		console.log('获取到的教师列表:', teacherList.value)
	} catch (error) {
		console.error('获取教师列表失败:', error)
		ElMessage.error('获取教师列表失败')
	}
}

const calculateStatistics = () => {
	const data = achievements.value
	
	statistics.totalCount = data.length
	statistics.journalCount = data.filter(item => item.type === '期刊论文').length
	statistics.conferenceCount = data.filter(item => item.type === '会议论文').length
	statistics.pendingCount = data.filter(item => item.status === 'PENDING').length
	
	// 期刊级别统计
	statistics.sci1Count = data.filter(item => item.journalLevel === 'SCI一区').length
	statistics.sci2Count = data.filter(item => item.journalLevel === 'SCI二区').length
	statistics.ssci1Count = data.filter(item => item.journalLevel === 'SSCI一区').length
	statistics.cssciCount = data.filter(item => item.journalLevel === 'CSSCI核心').length
}

const handleSearch = async () => {
	pagination.currentPage = 1
	
	// 如果输入了教师姓名，使用专门的作者搜索
	if (filters.teacherName && filters.teacherName.trim() !== '') {
		await searchByAuthorNameHandler(filters.teacherName)
	} else {
		// 否则显示所有成果
		await fetchAchievements()
	}
}

const debugData = () => {
	console.log('=== 调试信息 ===')
	console.log('筛选条件:', filters)
	console.log('成果列表:', achievements.value)
	console.log('教师列表:', teacherList.value)
	console.log('筛选后结果:', filteredAchievements.value)
	console.log('================')
}

const resetFilters = () => {
	Object.keys(filters).forEach(key => {
		filters[key] = ''
	})
	pagination.currentPage = 1
}

const viewAchievement = async (row) => {
	try {
		const response = await getAcademicAchievement(row.id)
		viewData.value = response.achievement || response
		showViewDialog.value = true
	} catch (error) {
		console.error('获取详情失败:', error)
		ElMessage.error('获取详情失败')
	}
}

const reviewAchievement = (row) => {
	currentReviewAchievement.value = row
	reviewForm.status = 'APPROVED'
	reviewForm.opinion = ''
	showReviewDialog.value = true
}

const submitReview = async () => {
	if (!currentReviewAchievement.value) return
	
	try {
		reviewing.value = true
		await reviewAcademicAchievement(currentReviewAchievement.value.id, reviewForm)
		ElMessage.success('审核完成')
		showReviewDialog.value = false
		fetchAchievements()
	} catch (error) {
		console.error('审核失败:', error)
		ElMessage.error('审核失败')
	} finally {
		reviewing.value = false
	}
}

const exportData = () => {
	ElMessage.info('导出功能待实现')
}

const handleSizeChange = (size) => {
	pagination.pageSize = size
	pagination.currentPage = 1
}

const handleCurrentChange = (page) => {
	pagination.currentPage = page
}

const getTypeTagType = (type) => {
	const types = {
		'期刊论文': 'primary',
		'会议论文': 'success',
		'书评': 'warning',
		'报刊理论文章': 'info'
	}
	return types[type] || 'info'
}

const getStatusType = (status) => {
	const types = {
		'PENDING': 'info',
		'APPROVED': 'success',
		'REJECTED': 'danger'
	}
	return types[status] || 'info'
}

const getStatusText = (status) => {
	const texts = {
		'PENDING': '待审核',
		'APPROVED': '已通过',
		'REJECTED': '已驳回'
	}
	return texts[status] || status
}

// 生命周期
onMounted(() => {
	fetchAchievements()
	fetchTeachers()
})
</script>

<style scoped>
.academic-achievement-overview {
	max-width: 1400px;
	margin: 0 auto;
}

.page-header {
	margin-bottom: 24px;
}

.page-title {
	margin: 0;
	color: #333;
	font-size: 24px;
	font-weight: 500;
}

.filter-card {
	margin-bottom: 20px;
}

.filter-section .el-form-item {
	margin-bottom: 16px;
}

.stats-card {
	margin-bottom: 20px;
}

.stats-section {
	padding: 20px 0;
}

.stat-item {
	text-align: center;
	padding: 20px;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	border-radius: 8px;
	color: white;
}

.stat-number {
	font-size: 32px;
	font-weight: bold;
	margin-bottom: 8px;
}

.stat-label {
	font-size: 14px;
	opacity: 0.9;
}

.table-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16px;
}

.table-title {
	font-size: 16px;
	font-weight: 500;
	color: #333;
}

.pagination-container {
	margin-top: 20px;
	text-align: center;
}

.authors-section h4 {
	margin-bottom: 16px;
	color: #333;
}

.author-info {
	margin-bottom: 4px;
}

.first-author {
	color: #e6a23c;
	font-weight: bold;
}

.corresponding-author {
	color: #409eff;
	font-weight: bold;
}

.author-order {
	color: #909399;
	font-size: 12px;
}

.more-authors {
	color: #909399;
	font-size: 12px;
	font-style: italic;
}

/* 响应式布局 */
@media (max-width: 1200px) {
	.academic-achievement-overview {
		max-width: 100%;
		padding: 0 16px;
	}
}

@media (max-width: 768px) {
	.filter-section .el-col {
		margin-bottom: 16px;
	}
	
	.stats-section .el-col {
		margin-bottom: 16px;
	}
}
</style>
